const db = uniCloud.database();
const dbCmd = db.command;
const $ = db.command.aggregate;
module.exports = async function(options = {}) {
	const { characterId } = options;
	const token = this.getUniIdToken();
	if (!token || !characterId) {
		throw new Error('非法访问');
	}
	const [groupList1, groupList2] = await Promise.all([
		db.collection('a-dz-group-list')
		.aggregate()
		.match({
			characterId
		})
		.lookup({
			from: 'a-dz-group-apply-list',
			let: {
				mainid: '$groupCode'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
					$.eq(['$groupCode', '$$mainid']),
					$.eq(['$characterId', characterId])
				])))
				.done(),
			as: 'applyList'
		})
		.project({
			groupName: 1,
			groupCode: 1,
			characterId: 1,
			status: 1,
			applyStatus: {
				$arrayElemAt: ["$applyList.applyStatus", 0]
			}
		})
		.end(),
		db.collection('a-dz-group-apply-list')
		.aggregate()
		.match({
			characterId
		})
		.lookup({
			from: 'a-dz-group-list',
			let: {
				mainid: '$groupCode'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
					$.eq(['$groupCode', '$$mainid'])
				])))
				.done(),
			as: 'groupList'
		})
		.project({
			applyStatus: 1,
			groupCode: 1,
			characterId: {
				$arrayElemAt: ["$groupList.characterId", 0]
			},
			groupName: {
				$arrayElemAt: ["$groupList.groupName", 0]
			},
			status: {
				$arrayElemAt: ["$groupList.status", 0]
			}
		})
		.end()
	])
	return {
		code: 0,
		data: groupList1.data.concat(groupList2.data),
		msg: '获取成功'
	}
}